
<!DOCTYPE HTML>
<html lang="" >
    <head>
        <meta charset="UTF-8">
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <title>3.4 多对多 · GitBook</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="description" content="">
        <meta name="generator" content="GitBook 3.2.2">
        
        
        
    
    <link rel="stylesheet" href="../gitbook/style.css">

    
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-highlight/website.css">
                
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-search/search.css">
                
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-fontsettings/website.css">
                
            
        

    

    
        
    
        
    
        
    
        
    
        
    
        
    

        
    
    
    <meta name="HandheldFriendly" content="true"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../gitbook/images/apple-touch-icon-precomposed-152.png">
    <link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">

    
    <link rel="next" href="3.5多态一对多.html" />
    
    
    <link rel="prev" href="3.3一对多.html" />
    

    </head>
    <body>
        
<div class="book">
    <div class="book-summary">
        
            
<div id="book-search-input" role="search">
    <input type="text" placeholder="Type to search" />
</div>

            
                <nav role="navigation">
                


<ul class="summary">
    
    

    

    
        
        
    
        <li class="chapter " data-level="1.1" data-path="../">
            
                <a href="../">
            
                    
                    Introduction
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2" data-path="1.写在前面的话.html">
            
                <a href="1.写在前面的话.html">
            
                    
                    写在前面的话
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3" data-path="2.搭建环境.html">
            
                <a href="2.搭建环境.html">
            
                    
                    第一章 搭建环境
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4" >
            
                <span>
            
                    
                    第二章 模型定义
            
                </span>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.4.1" data-path="3.sequelize 实例变量.html">
            
                <a href="3.sequelize 实例变量.html">
            
                    
                    2.1 实例变量方法
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.2" data-path="4.定义一个模型.html">
            
                <a href="4.定义一个模型.html">
            
                    
                    2.2 定义一个模型
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.3" data-path="5.模型字段类型.html">
            
                <a href="5.模型字段类型.html">
            
                    
                    2.3 模型字段类型
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.4" data-path="6.导入与配置.html">
            
                <a href="6.导入与配置.html">
            
                    
                    2.3 导入与配置
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.5" data-path="3模型关系.html">
            
                <a href="3模型关系.html">
            
                    
                    第三章 模型关系
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.5.1" data-path="3.1属于.html">
            
                <a href="3.1属于.html">
            
                    
                    3.1 属于
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.2" data-path="3.2包含.html">
            
                <a href="3.2包含.html">
            
                    
                    3.2 包含
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.3" data-path="3.3一对多.html">
            
                <a href="3.3一对多.html">
            
                    
                    3.3 一对多
            
                </a>
            

            
        </li>
    
        <li class="chapter active" data-level="1.5.4" data-path="3.4多对多.html">
            
                <a href="3.4多对多.html">
            
                    
                    3.4 多对多
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.5" data-path="3.5多态一对多.html">
            
                <a href="3.5多态一对多.html">
            
                    
                    3.5 多态一对多
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.6" data-path="3.6多态多对多.html">
            
                <a href="3.6多态多对多.html">
            
                    
                    3.6 多态多对多
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.7" data-path="3.7关系嵌套.html">
            
                <a href="3.7关系嵌套.html">
            
                    
                    3.7 关系嵌套
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.6" data-path="4模型查询.html">
            
                <a href="4模型查询.html">
            
                    
                    第四章 模型查询
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.7" data-path="5查询范围.html">
            
                <a href="5查询范围.html">
            
                    
                    第五章 查询范围 Scope (预定义查询条件)
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.8" data-path="6生命周期函数.html">
            
                <a href="6生命周期函数.html">
            
                    
                    第六章 生命周期函数 Hook
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9" data-path="7migrate.html">
            
                <a href="7migrate.html">
            
                    
                    第七章 数据库迁移 Migrate
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.10" data-path="8tabel2model.html">
            
                <a href="8tabel2model.html">
            
                    
                    第八章 根据 Table 生成 Model
            
                </a>
            

            
        </li>
    

    

    <li class="divider"></li>

    <li>
        <a href="https://www.gitbook.com" target="blank" class="gitbook-link">
            Published with GitBook
        </a>
    </li>
</ul>


                </nav>
            
        
    </div>

    <div class="book-body">
        
            <div class="body-inner">
                
                    

<div class="book-header" role="navigation">
    

    <!-- Title -->
    <h1>
        <i class="fa fa-circle-o-notch fa-spin"></i>
        <a href=".." >3.4 多对多</a>
    </h1>
</div>




                    <div class="page-wrapper" tabindex="-1" role="main">
                        <div class="page-inner">
                            
<div id="book-search-results">
    <div class="search-noresults">
    
                                <section class="normal markdown-section">
                                
                                <h1 id="&#x591A;&#x5BF9;&#x591A;">&#x591A;&#x5BF9;&#x591A;</h1>
<p>&#x5728;&#x5982;&#x4ECA;&#x7684;&#x793E;&#x4F1A;&#xFF0C;&#x6211;&#x4EEC;&#x975E;&#x5E38;&#x559C;&#x6B22;&#x7ED9;&#x4EBA;&#x6253;&#x4E0A;&#x6807;&#x7B7E;&#xFF0C;&#x6BD4;&#x5982; <code>&#x989C;&#x503C;&#x9006;&#x5929;</code>&#x3001;<code>&#x6696;&#x70D8;&#x70D8;</code>&#x3001;<code>&#x9AD8;&#x5BCC;&#x5E05;</code>&#x7B49;&#x7B49;&#x3002;&#x9AD8;&#x5BCC;&#x5E05;&#x5E76;&#x4E0D;&#x662F;&#x67D0;&#x4E00;&#x4E2A;&#x4EBA;&#x7684;&#x4E13;&#x5229;&#xFF0C;&#x4E00;&#x4E2A;&#x4EBA;&#x53EF;&#x4EE5;&#x88AB;&#x522B;&#x4EBA;&#x6253;&#x4E0A;&#x591A;&#x4E2A;&#x6807;&#x7B7E;&#xFF0C;&#x4E00;&#x4E2A;&#x6807;&#x7B7E;&#x4E5F;&#x53EF;&#x4EE5;&#x6253;&#x5728;&#x591A;&#x4E2A;&#x4EBA;&#x4E0A;&#x9762;&#x3002;&#x8FD9;&#x5C31;&#x662F;&#x591A;&#x5BF9;&#x591A;&#x5173;&#x7CFB;&#x3002;</p>
<p>&#x58F0;&#x660E;&#x591A;&#x5BF9;&#x591A;&#x5173;&#x7CFB;&#x9700;&#x8981;&#x7528;&#x5230;<code>belongsToMany</code>&#x65B9;&#x6CD5;&#x3002;</p>
<pre><code>User.beblongsToMany(Tag, {through: &apos;user_tag&apos;});
Tag.belongsToMany(User, {through: &apos;user_tag&apos;});
</code></pre><p>&#x5728;&#x591A;&#x5BF9;&#x591A;&#x5173;&#x7CFB;&#x7684;&#x8868;&#x7ED3;&#x6784;&#x4E2D;&#xFF0C;&#x65E0;&#x8BBA;&#x6211;&#x4EEC;&#x628A;&#x5173;&#x7CFB; id &#x5B58;&#x5728;&#x53CC;&#x65B9;&#x7684;&#x4EFB;&#x4F55;&#x4E00;&#x4E2A;&#x8868;&#x4E2D;&#xFF0C;&#x4F1A;&#x51FA;&#x73B0;&#x4E0A;&#x4E00;&#x8282;&#x6240;&#x63D0;&#x5230;&#x7684;&#x4F7F;&#x7528;<code>Book.hasOne(User)</code>&#x58F0;&#x660E;&#x5173;&#x7CFB;&#xFF0C;&#x6709;&#x6570;&#x636E;&#x5197;&#x4F59;&#x7684;&#x95EE;&#x9898;&#xFF0C;&#x6240;&#x4EE5;&#x5728;&#x591A;&#x5BF9;&#x591A;&#x5173;&#x7CFB;&#x4E0B;&#x7684;&#x8868;&#x7ED3;&#x6784;&#x9700;&#x8981;&#x7B2C;&#x4E09;&#x4E2A;&#x8868;&#x6765;&#x4FDD;&#x5B58;&#x5B83;&#x4EEC;&#x4E4B;&#x95F4;&#x7684;&#x5173;&#x7CFB;&#x3002;</p>
<p>&#x800C;&#x8FD9;&#x7B2C;&#x4E09;&#x5F20;&#x8868;&#xFF0C;&#x5C31;&#x662F;&#x4E0A;&#x9762;&#x7684; user_tag &#x3002;&#x91CC;&#x9762;&#x6709;&#x4E00;&#x4E2A; userId &#x548C;&#x4E00;&#x4E2A; tagId &#x5B57;&#x6BB5;&#x3002;</p>
<h3 id="&#x5B9E;&#x4F8B;">&#x5B9E;&#x4F8B;</h3>
<h4 id="1&#x65B0;&#x5EFA;-tagts-&#x6587;&#x4EF6;">1.&#x65B0;&#x5EFA; tag.ts &#x6587;&#x4EF6;</h4>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> Sequelize from <span class="hljs-string">&apos;sequelize&apos;</span>;
<span class="hljs-keyword">import</span> {UserAttributes, UserInstance} from <span class="hljs-string">&apos;./user&apos;</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">interface</span> TagAttributes {
  name: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">interface</span> TagInstance <span class="hljs-keyword">extends</span> Sequelize.Instance&lt;TagAttributes&gt;, TagAttributes {
  id: <span class="hljs-built_in">number</span>;

  getUsers: Sequelize.BelongsToManyGetAssociationsMixin&lt;UserInstance&gt;,
  addUsers: Sequelize.BelongsToManyAddAssociationsMixin&lt;UserInstance, <span class="hljs-built_in">number</span>, <span class="hljs-built_in">any</span>&gt;,
  addUser: Sequelize.BelongsToManyAddAssociationMixin&lt;UserInstance, <span class="hljs-built_in">number</span>, <span class="hljs-built_in">any</span>&gt;,
  setUser: Sequelize.BelongsToManySetAssociationsMixin&lt;UserInstance, <span class="hljs-built_in">number</span>, <span class="hljs-built_in">any</span>&gt;,
  countUsers: Sequelize.BelongsToManyCountAssociationsMixin,
  createUser: Sequelize.BelongsToManyCreateAssociationMixin&lt;UserAttributes, UserInstance, <span class="hljs-built_in">any</span>&gt;,
  hasUser: Sequelize.BelongsToManyHasAssociationMixin&lt;UserInstance, <span class="hljs-built_in">number</span>&gt;,
  hasUsers: Sequelize.BelongsToManyHasAssociationsMixin&lt;UserInstance, <span class="hljs-built_in">number</span>&gt;,
  removeUser: Sequelize.BelongsToManyRemoveAssociationMixin&lt;UserInstance, <span class="hljs-built_in">number</span>&gt;,
  removeUsers: Sequelize.BelongsToManyRemoveAssociationsMixin&lt;UserInstance, <span class="hljs-built_in">number</span>&gt;,

}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">TagDefine</span>(<span class="hljs-params">sequelize: Sequelize.Sequelize, dataTypes: Sequelize.DataTypes</span>): <span class="hljs-title">Sequelize</span>.<span class="hljs-title">Model</span>&lt;<span class="hljs-title">TagInstance</span>, <span class="hljs-title">TagAttributes</span>&gt;  </span>{
    <span class="hljs-keyword">const</span> S = dataTypes;
    <span class="hljs-keyword">const</span> Tag = sequelize.define&lt;TagInstance, TagAttributes&gt;(<span class="hljs-string">&apos;Tag&apos;</span>, {
        name: S.STRING
    }, {
        timestamps: <span class="hljs-literal">false</span>
    });

    (Tag as <span class="hljs-built_in">any</span>).associate = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"><span class="hljs-keyword">this</span>: <span class="hljs-keyword">typeof</span> Tag, models</span>)</span>{
        <span class="hljs-keyword">this</span>.belongsToMany(models.User, {through: <span class="hljs-string">&apos;user_tag&apos;</span>});
    }

    <span class="hljs-keyword">return</span> Tag;
}
</code></pre>
<h4 id="2&#x5728;-userts-&#x6DFB;&#x52A0;&#x5173;&#x7CFB;&#x4EE3;&#x7801;">2.&#x5728; user.ts &#x6DFB;&#x52A0;&#x5173;&#x7CFB;&#x4EE3;&#x7801;</h4>
<pre><code class="lang-ts">  getTags: Sequelize.BelongsToManyGetAssociationsMixin&lt;TagInstance&gt;,
  addTags: Sequelize.BelongsToManyAddAssociationsMixin&lt;TagInstance, <span class="hljs-built_in">number</span>, <span class="hljs-built_in">any</span>&gt;,
  addTag: Sequelize.BelongsToManyAddAssociationMixin&lt;TagInstance, <span class="hljs-built_in">number</span>, <span class="hljs-built_in">any</span>&gt;,
  setTag: Sequelize.BelongsToManySetAssociationsMixin&lt;TagInstance, <span class="hljs-built_in">number</span>, <span class="hljs-built_in">any</span>&gt;,
  countTags: Sequelize.BelongsToManyCountAssociationsMixin,
  createTag: Sequelize.BelongsToManyCreateAssociationMixin&lt;TagAttributes, TagInstance, <span class="hljs-built_in">any</span>&gt;,
  hasTag: Sequelize.BelongsToManyHasAssociationMixin&lt;TagInstance, <span class="hljs-built_in">number</span>&gt;,
  hasTags: Sequelize.BelongsToManyHasAssociationsMixin&lt;TagInstance, <span class="hljs-built_in">number</span>&gt;,
  removeTag: Sequelize.BelongsToManyRemoveAssociationMixin&lt;TagInstance, <span class="hljs-built_in">number</span>&gt;,
  removeTags: Sequelize.BelongsToManyRemoveAssociationsMixin&lt;TagInstance, <span class="hljs-built_in">number</span>&gt;,
</code></pre>
<pre><code class="lang-ts"> (User as <span class="hljs-built_in">any</span>).associate = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"><span class="hljs-keyword">this</span>: <span class="hljs-keyword">typeof</span> User,models</span>)</span>{
   <span class="hljs-comment">// this.hasOne(models.Book);</span>
   <span class="hljs-keyword">this</span>.hasMany(models.Book);
   <span class="hljs-keyword">this</span>.belongsToMany(models.Tag, { through: <span class="hljs-string">&apos;user_tag&apos;</span>});
}
</code></pre>
<h4 id="3&#x5728;-indexts-&#x91CC;&#x9762;&#x6DFB;&#x52A0;&#x9A8C;&#x8BC1;&#x4EE3;&#x7801;">3.&#x5728; index.ts &#x91CC;&#x9762;&#x6DFB;&#x52A0;&#x9A8C;&#x8BC1;&#x4EE3;&#x7801;</h4>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> TagDefined, {TagAttributes, TagInstance} from <span class="hljs-string">&apos;./tag&apos;</span>;

<span class="hljs-keyword">const</span> Tag = sequelize.import&lt;TagInstance, TagAttributes&gt;(<span class="hljs-string">&apos;./tag&apos;</span>);

<span class="hljs-keyword">let</span> user = await User.create({email:<span class="hljs-string">&apos;belovedyogurt@gmail.com&apos;</span>,name: <span class="hljs-string">&apos;yugo&apos;</span>})
await user.createTag({name: <span class="hljs-string">&apos;&#x840C;&#x65B0;&apos;</span>}); <span class="hljs-comment">// &#x4E3A; yugo &#x6DFB;&#x52A0;&#x4E00;&#x4E2A;&#x6807;&#x7B7E;</span>

<span class="hljs-keyword">let</span> tag = (await Tag.findAll())[<span class="hljs-number">0</span>]; <span class="hljs-comment">// &#x62FF;&#x5230; tag &#x8868;&#x4E2D;&#x7B2C;&#x4E00;&#x6761;&#x6570;&#x636E;</span>

<span class="hljs-keyword">const</span> tagUser = (await tag.getUsers())[<span class="hljs-number">0</span>]; <span class="hljs-comment">// &#x62FF;&#x5230;&#x8BE5;&#x6807;&#x7B7E;&#x5173;&#x8054;&#x7684;&#x7528;&#x6237;&#x7684;&#x7B2C;&#x4E00;&#x4E2A;</span>

<span class="hljs-built_in">console</span>.log(user.id == tagUser.id); <span class="hljs-comment">// &#x4FE9;&#x8FB9;&#x67E5;&#x51FA;&#x6765;&#x7684; user &#x662F;&#x5426;&#x76F8;&#x7B49;</span>
</code></pre>
<p>&#x8FD0;&#x884C;&#x4E4B;&#x540E;&#x53EF;&#x4EE5;&#x5F97;&#x5230;&#x4E00;&#x4E2A; true &#xFF0C;&#x8BF4;&#x660E;&#x903B;&#x8F91;&#x6B63;&#x786E;&#x3002;&#x800C;&#x4E14;&#x5728;&#x6570;&#x636E;&#x5E93;&#x4E2D;&#x4E5F;&#x521B;&#x5EFA;&#x4E86;<code>user_tag</code>&#x5173;&#x8054;&#x8868;&#xFF0C;&#x5B8C;&#x6210;&#x4EE5;&#x4E0A;&#x4EE3;&#x7801;&#x8FD0;&#x884C;&#x4E4B;&#x540E;&#x4FBF;&#x53EF;&#x770B;&#x5230;&#x6570;&#x636E;&#x5E93;&#x4E2D;&#x5DF2;&#x5B58;&#x6570;&#x636E;&#x3002;</p>

                                
                                </section>
                            
    </div>
    <div class="search-results">
        <div class="has-results">
            
            <h1 class="search-results-title"><span class='search-results-count'></span> results matching "<span class='search-query'></span>"</h1>
            <ul class="search-results-list"></ul>
            
        </div>
        <div class="no-results">
            
            <h1 class="search-results-title">No results matching "<span class='search-query'></span>"</h1>
            
        </div>
    </div>
</div>

                        </div>
                    </div>
                
            </div>

            
                
                <a href="3.3一对多.html" class="navigation navigation-prev " aria-label="Previous page: 3.3 一对多">
                    <i class="fa fa-angle-left"></i>
                </a>
                
                
                <a href="3.5多态一对多.html" class="navigation navigation-next " aria-label="Next page: 3.5 多态一对多">
                    <i class="fa fa-angle-right"></i>
                </a>
                
            
        
    </div>

    <script>
        var gitbook = gitbook || [];
        gitbook.push(function() {
            gitbook.page.hasChanged({"page":{"title":"3.4 多对多","level":"1.5.4","depth":2,"next":{"title":"3.5 多态一对多","level":"1.5.5","depth":2,"path":"document/3.5多态一对多.md","ref":"./document/3.5多态一对多.md","articles":[]},"previous":{"title":"3.3 一对多","level":"1.5.3","depth":2,"path":"document/3.3一对多.md","ref":"./document/3.3一对多.md","articles":[]},"dir":"ltr"},"config":{"gitbook":"*","theme":"default","variables":{},"plugins":["livereload"],"pluginsConfig":{"livereload":{},"highlight":{},"search":{},"lunr":{"maxIndexSize":1000000,"ignoreSpecialCharacters":false},"sharing":{"facebook":true,"twitter":true,"google":false,"weibo":false,"instapaper":false,"vk":false,"all":["facebook","google","twitter","weibo","instapaper"]},"fontsettings":{"theme":"white","family":"sans","size":2},"theme-default":{"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"showLevel":false}},"structure":{"langs":"LANGS.md","readme":"README.md","glossary":"GLOSSARY.md","summary":"SUMMARY.md"},"pdf":{"pageNumbers":true,"fontSize":12,"fontFamily":"Arial","paperSize":"a4","chapterMark":"pagebreak","pageBreaksBefore":"/","margin":{"right":62,"left":62,"top":56,"bottom":56}},"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"}},"file":{"path":"document/3.4多对多.md","mtime":"2017-06-28T03:29:36.000Z","type":"markdown"},"gitbook":{"version":"3.2.2","time":"2017-06-28T08:29:37.466Z"},"basePath":"..","book":{"language":""}});
        });
    </script>
</div>

        
    <script src="../gitbook/gitbook.js"></script>
    <script src="../gitbook/theme.js"></script>
    
        
        <script src="../gitbook/gitbook-plugin-livereload/plugin.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-search/search-engine.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-search/search.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-lunr/lunr.min.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-lunr/search-lunr.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-sharing/buttons.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-fontsettings/fontsettings.js"></script>
        
    

    </body>
</html>

